<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px"  
  >
    <el-form-item label="长期/临时" prop="repeatIncaditor" style="margin-bottom: 8px">
      <el-radio-group v-model="form.repeatIncaditor">
        <el-radio
          v-for="dict in dictDataMap['order_type']"
          :key="dict.dictValue"
          :border="true"
          :value="dict.dictValue"
        >{{ dict.dictLabel }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="消耗品库房" prop="implementDept">
      <el-select v-model="form.implementDept" 
                  placeholder="请输入消耗品库房" >
        <el-option v-for="materialVsDept in materialVsDeptList" :key="materialVsDept.storageId"
                    :label="materialVsDept.storageName" :value="materialVsDept.storageId"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="消耗品名称" prop="itemName">
      <el-input v-if="isShow" v-model="form.itemName"
                @focus="isShowItemNameFocus()">
      </el-input>
      <automatic-completion v-else
                            ref="itemAutomatic" v-model="form.itemName"
                            :dict-array="dictArray"
                            :table-body-list="tableBodyList"
                            :table-head-list="tableHeadList"
                            :title="itemTitle"
                            :leftSpan="24" :rightSpan="0"
                            style="width: 100%" 
                            @itemNameInput="itemNameInput"
                            @row-click="rowClick"
      />
    </el-form-item>
    <el-form-item label="数量" prop="sumNum">
      <el-input v-model="form.sumNum" placeholder="请输入数量" @blur="numInput"/>
    </el-form-item>
    <el-form-item label="天数" prop="abidance">
      <el-input v-model="form.abidance" placeholder="请输入天数"/>
    </el-form-item>
    <el-form-item label="频次" prop="performFreq">
      <perform-index
        ref="performIndex"
        :placeholder="'请选择频次'"
        :value="form.performFreq"
        style="width: 100%"
        @performFreqInfoChange="performFreqInfoChange"
      />
    </el-form-item>
    <el-form-item label="单价" prop="price">
      <el-input v-model="form.price" :disabled="true" placeholder="请输入单价">
        <template #append>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="总价格" prop="sumPrice">
      <el-input v-model="form.sumPrice" :disabled="true" placeholder="请输入总价格">
        <template #append>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="备注信息" prop="remarks">
      <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
    </el-form-item> 
    <el-button style="float: right" :loading="buttonLoading" type="primary" @click="submitFormOk">开 单</el-button> 
      
  </el-form>
    
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {jsonStrInObj, materialExportList} from "@/utils/autoComplete";
import { autoExportList } from "@/api/material/materialStock"; 
import {idNo, positiveNumber} from "@/utils/myRules"; 
import {getMaterialVsDeptList} from "@/api/material/materialStorageDept.ts"
import {addOrders} from "@/api/orders/orders.ts"

const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "clinic_or_visit",
    "charge_flag_dict", "order_type",
    "sys_yes_no","chinese_western_type",
    'diagnosis_type', 'grant_flag'
  )
);

// 项目选择自动补全窗体名称
const itemTitle = ref("选择耗材");
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(materialExportList));
// 项目选择自动补全表格数据
const tableBodyList = ref([]);
// 项目选择自动补全字典数组
const dictArray = ref(["bill_item_class_dict"]);
const itemAutomatic = ref();
const emits = defineEmits(["submitFormOk"]);
const props = defineProps({
  inoroutFlag: {
    type: String,
    default: "",
  },
  visitId: {
    type: String,
    default: "",
  },
  patientId: {
    type: String,
    default: "",
  }
});
const clinicId = ref(proxy.$clinicId);
const visitId = ref(props.visitId);
const patientId = ref(props.patientId);
const inoroutFlag = ref(props.inoroutFlag);
const formRef = ref(); 
const buttonLoading = ref(false); 
const ids = ref([]); 
// 消耗品库房list
const materialVsDeptList = ref<any>([])
const form = ref<any>({
  id: "",
  clinicId: clinicId.value,
  clinicOrdersId: "",
  patientId: patientId.value,
  visitId: visitId.value,
  inoroutFlag: inoroutFlag.value,
  confirmFlag: "N",
  chargeFlag: "1",
  stockId: "",
  groupNo: "",
  applyNo: "",
  abidance: 1,
  applyUser: userInfo.userId,
  implementDept: "",
  applyDept: userInfo.loginDeptId,
  performFreq: "",
  itemName: "",
  orderText: "",
  sumNum: 1,
  orgId: userInfo.orgId,
  remarks: "",
  isApply: "N",
  isPhy: "N",
  itemClass: "I",
  unitsStr: "",
  supplierName: "",
  packageSpec: "",
  isClinicFee: "",
  mark: "",
  clinicItemName: "",
  itemInfo: "",
  isFiltrationContrastExist: true,
  // 是否附带费用 true：是   false：否
  whetherToComeInAttached: false,
  icdCode: "",
  icdName: "",
  orderClass: "2",
  billingAttr: "1",
  orderStatus: "1",
  isMedical: "N",
  repeatIncaditor:"1"
});
const autoForm = ref<any>({
  clinicItemName: "",
  itemInfo: "",
  orgId: userInfo.orgId,
  storageId: "",
  isFiltrationContrastExist: true,
  notInSelect: [],
});
  
const rules = ref<any>({
  repeatIncaditor: [{required: true, message: "长期临时不能为空", trigger: "change"}],
  itemName: [{required: true, message: "项目不能为空", trigger: "change"}],
  implementDept: [{required: true, message: "执行科室不能为空", trigger: "change"}],
  sumNum: [{required: true, validator: positiveNumber, trigger: "blur"}],
  abidance: [{required: true, validator: positiveNumber, trigger: "blur"}],
});

  

/** 项目列表行点击事件 */
function rowClick(row: any) {
  itemAutomatic.value.closePopover(); 
  isShow.value = true 
  
  form.value.clinicItemId = row.materialPriceId;
  form.value.stockId = row.stockId;
  form.value.itemName = row.materialName;
  form.value.orderText = row.materialName;
  form.value.itemCode = row.materialCode;
  form.value.itemClass = 'I';
  form.value.itemSpec = row.currentSpec;
  form.value.supplierName = row.firmName;
  autoForm.value.clinicItemName = row.materialName;
  const subTotal = Number(row.retailPrice) ? Number(row.retailPrice) : 0;
  form.value.price = subTotal.toFixed(2);
  form.value.tradePrice = row.purchasePrice;
  form.value.packageSpec = row.packageSpec;
  form.value.unitsStr = row.packSize==='1' ? row.minUnitsName:row.packageUnitsName;
  form.value.sumPrice = (subTotal * form.value.sumNum).toFixed(2);
  form.value.storageName = row.storageName; 
  form.value.storageId = row.storageId; 
  tableBodyList.value = [];
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}

/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName;
  getListMaterial();
}

/** 默认频次选择事件 */
function performFreqInfoChange(obj: any) {
  form.value.performFreq = obj.freqId;
}

 

/** 自动补全后台查询 */
function getListMaterial() {
  if (autoForm.value.itemInfo) { 
    autoForm.value.orgId = userInfo.orgId; 
    autoForm.value.storageId = form.value.implementDept;
    console.log(autoForm.value);
    
    autoExportList(autoForm.value).then((res) => {
      tableBodyList.value = res.data;
      // 打开自动补全弹出框
      itemAutomatic.value.init();
    });
  } else {
    tableBodyList.value = [];
  }
}

/** 数量改变事件 */
function numInput() {
  form.value.sumPrice = (form.value.price * form.value.sumNum).toFixed(2);
}

 
 
/** 提交按钮 */
function submitForm() {
  buttonLoading.value = true;
  

} 
/**
 * 诊断弹出框确认按钮
 */
function submitFormOk() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      let ordersList = new Array<any>()
      ordersList.push(form.value)
      const data = {
        "ordersList": ordersList,
        "orgId": userInfo.orgId,
        patientId: patientId.value,
        visitId: visitId.value,
      }
      console.log("data",data)
      //return 
      addOrders(data).then(() => {
        ElMessage.success("开单成功")
        emits("submitFormOk");
      })
    }
  });
}
 

// 以科室id查询对应的药房、药库信息
function getMaterialVsDeptListFun() {
  let data = {
    deptId: userInfo.loginDeptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("1,2,0", ","),
    storageTypeArray: proxy.$stringToArray("3,4", ",")
  }
  getMaterialVsDeptList(data).then((res: any) => {
    materialVsDeptList.value = res.data 
     
  })
}
 
getMaterialVsDeptListFun();
defineExpose({
   
})
</script>

<style scoped>
.app-container {
  padding: 0px !important;
}
</style>